package com.itheima.dao;

import com.itheima.domain.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class MyBatisTest01 {
    private SqlSession sqlSession=null;
    @Before
    public void prepare() throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        sqlSession = factory.openSession();
    }
    @After
    public void destroy(){
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void findAll() throws Exception{
        List<Student> list = sqlSession.selectList("StudentMapper.findAll");
        for (Student stu : list) {
            System.out.println(stu);
        }
    }

    @Test
    public  void findById() throws Exception{
        Student stu = sqlSession.selectOne("StudentMapper.findById",1);
        System.out.println(stu);
    }

    @Test
    public void addStu(){
        Student stu = new Student();
        stu.setName("张君宝");
        stu.setAge(25);
        int insert = sqlSession.insert("StudentMapper.addStu", stu);
        System.out.println(insert);
    }

    @Test
    public void deleteById(){
        int delete = sqlSession.delete("StudentMapper.deleteById", 2);
        System.out.println(delete);
    }

    @Test
    public void update(){
        Student stu = new Student();
        stu.setId(7);
        stu.setName("张三丰");
        stu.setAge(125);
        int update = sqlSession.update("StudentMapper.update", stu);
        System.out.println(update);
    }


}
